﻿using Common.Net;
using Common.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace KCPServer.Core.Net
{
    public class ClientPeer
    {
        public int clientId;
        public TcpClient tcp;
        NServer nServer;
        NetworkStream stream;
        TcpPack tcpPack = new TcpPack();
       
        public ClientPeer(TcpClient tcp, NServer server)
        {
            this.tcp = tcp;
            this.nServer = server;
            Task.Run(TcpReceiveData);
        }
        async void TcpReceiveData()
        {
            try
            {
                stream = tcp.GetStream();
                while (tcp.Connected && tcp.Client.Connected)
                {
                    int bytesRead = await stream.ReadAsync(tcpPack.Data, tcpPack.StartIndex, tcpPack.RemainSize);
                    tcpPack.ReceiveData(bytesRead, HandleMsgInfo);
                }
                Disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine("Tcp错误：" + e.Message);
                Disconnect();
            }
            finally
            {
                Console.WriteLine("ClientPeer 断开：" + clientId);
                Disconnect();
            }
        }

        void HandleMsgInfo(RequestType arg1, object arg2)
        {
            lock (nServer.delayMsgInfo)
            {
                Console.WriteLine("[收到客户端的数据]" + clientId);
                nServer.delayMsgInfo.Enqueue(new MsgInfo()
                {
                    sendId = clientId,
                    requestType = arg1,
                    vo = arg2
                });
            }
        }

        public void send(RequestType type, object vo)
        {
            SendByTcp(new MsgInfo()
            {
                requestType = type,
                vo = vo,
                sendId = clientId
            });
        }

        void SendByTcp(MsgInfo msgInfo)
        {
            var data = TcpPack.WriteData(msgInfo);
            stream.Write(data, 0, data.Length);
        }
        void Disconnect()
        {

        }
    }
}
